package com.anlogic.sdk.utils;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

import org.eclipse.debug.internal.core.StreamDecoder;

@SuppressWarnings("restriction")
public class StreamUtils {

	public static StreamDecoder newStreamDecoder(Charset charset) {
		return new StreamDecoder(charset);
	}

	public static byte[] getBytes(char[] chars) {
		Charset cs = Charset.forName("UTF-8");
		CharBuffer cb = CharBuffer.allocate(chars.length);
		cb.put(chars);
		cb.flip();
		ByteBuffer bb = cs.encode(cb);
		return bb.array();
	}

	public static byte[] getBytes(char[] chars, Charset charset) {
		CharBuffer cb = CharBuffer.allocate(chars.length);
		cb.put(chars);
		cb.flip();
		ByteBuffer bb = charset.encode(cb);
		return bb.array();
	}
	
	public static char[] getChars(byte[] bytes) {
		Charset cs = Charset.forName("UTF-8");
		ByteBuffer bb = ByteBuffer.allocate(bytes.length);
		bb.put(bytes);
		bb.flip();
		CharBuffer cb = cs.decode(bb);
		return cb.array();
	}
	
	public static char[] getChars(byte[] bytes, Charset charset) {
		ByteBuffer bb = ByteBuffer.allocate(bytes.length);
		bb.put(bytes);
		bb.flip();
		CharBuffer cb = charset.decode(bb);
		return cb.array();
	}

	public static byte[] charToByte(char c) {
		byte[] b = new byte[2];
		b[0] = (byte) ((c & 0xFF00) >> 8);
		b[1] = (byte) (c & 0xFF);
		return b;
	}

	public static char byteToChar(byte[] b) {
		char c = (char) (((b[0] & 0xFF) << 8) | (b[1] & 0xFF));
		return c;
	}
	
	public static byte[] stringToByte(String str, Charset charset) {
		byte[] bytes = str.getBytes(charset);
		return bytes;
	}
	
	public static String byteToString(byte[] b, Charset charset) {
		String str = new String(b, charset);
		return str;
	}
}
